package cn.heima.heima_netty.netty.c3.pipeline;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * Channel关闭
 * 连接eventLoopServer
 * @author felix
 * @date 2025/2/12 10:39
 */
@Slf4j
public class Client {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture future = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder())
                                .addLast(new LoggingHandler(LogLevel.DEBUG));
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));

        Channel channel = future.sync().channel();
        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while(true){
                String line = scanner.nextLine();
                if(line.equals("q")){
                    log.debug("线程内退出...");
                    channel.close();
                    break;
                }
                channel.writeAndFlush(line);
            }
        },"input").start();
        //1.同步关闭。阻塞主线程，优雅关闭group
        ChannelFuture closeFuture = channel.closeFuture();
//        closeFuture.sync();
//        log.debug("处理关闭之后的操作...");
//        group.shutdownGracefully();

        //2.异步关闭。NIO线程调用平滑关闭
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
            log.debug("处理关闭之后的操作...");
                group.shutdownGracefully();
            }
        });
    }
}
